/**
 * Created by gaomeng on 2017/1/15.
 */
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;

public class VideoDownload {
    static Connection conn=null;
    public static void downloadTopThree(String[] categoriesList) throws InterruptedException, SQLException {
        for (String categories : categoriesList) {
            topThree(categories);
        }
    }

    //下载某一类别下的top3视频
    public static void topThree(String categories) throws InterruptedException, SQLException {
        List<Bsite> datalist = JDBC.searchTopThree(conn,categories);
        for (Bsite datas : datalist) {
            System.out.println(datas.getTitle());

            //获取真实下载地址，并下载视频
            String absoluteUrl = getAbsoluteUrl(datas.getUrl());
            if (absoluteUrl!= null) {
                downloadVideo(absoluteUrl);
            } else {
                System.out.println(datas.getTitle() + "未获取到下载地址");
            }
            System.out.println(datas.getFavorite());
        }
    }


    public static String getUrl(String url) {
        String content = Test.getJson(url);
        Document doc = Jsoup.parse(content);
        Elements elements = doc.select("a");
        for (Element element : elements) {
            String downUrl = element.attr("href");
            //匹配下载链接
            if (downUrl.contains("http://www.bilibilijj.com/Files/DownLoad/") && downUrl.contains("mp4")) {
                return downUrl;
            }
        }
        return null;
    }

    //通过URL下载视频
    public static void downloadVideo(String url1) {
        String filePath = "/Users/Alison/Movies/Bsite/";
        String[] names = url1.split("/");
        String name = names[names.length - 2];
        try {
            URL url = new URL(url1);
            URLConnection conn = url.openConnection();
            File fileD = new File(filePath);
            //若文件夹路径不存在则新建
            if (!fileD.exists() && !fileD.isDirectory()) {
                fileD.mkdirs();
            }
            File file = new File(filePath + name);
            if (!file.exists()) {
                try {file.createNewFile();}
                catch (IOException e) {e.printStackTrace();}
            }
            FileUtils.copyURLToFile(url, file);
            System.out.println("下载成功");
        }
        catch (MalformedURLException e) {e.printStackTrace();}
        catch (IOException e) {e.printStackTrace();}
    }
}
